<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { getCommunityList, getUserCommunityList } from '@/api/community';
import { Community } from '@/api/community/type';
import { router } from '@/router';
import { showNotify } from 'vant';

const myCommunitiesLoading = ref(true);
const allCommunitiesLoading = ref(true);
const myCommunities = ref<Community[]>([]);
const allCommunities = ref<Community[]>([]);
const searchValue = ref('');
const refreshing = ref(false);

// 加载数据
const loadData = async () => {
  try {
    // 并行加载两个请求
    await Promise.all([
      loadMyCommunities(),
      loadAllCommunities()
    ]);
  } catch (error) {
    console.error('加载社区数据失败:', error);
    showNotify({
      type: 'danger',
      message: '加载社区数据失败',
      position: 'top'
    });
  } finally {
    refreshing.value = false;
  }
};

// 加载我的社区
const loadMyCommunities = async () => {
  myCommunitiesLoading.value = true;
  try {
    const res = await getUserCommunityList();
    myCommunities.value = res.data || [];
  } catch (error) {
    console.error('加载我的社区失败:', error);
  } finally {
    myCommunitiesLoading.value = false;
  }
};

// 加载所有社区
const loadAllCommunities = async () => {
  allCommunitiesLoading.value = true;
  try {
    const res = await getCommunityList();
    allCommunities.value = res.data || [];
  } catch (error) {
    console.error('加载推荐社区失败:', error);
  } finally {
    allCommunitiesLoading.value = false;
  }
};

// 刷新数据
const onRefresh = async () => {
  refreshing.value = true;
  await loadData();
};

// 搜索社区
const onSearch = (value: string) => {
  console.log('搜索:', value);
  // 这里可以实现实际的搜索功能
};

// 跳转到社区详情
const navigateToCommunity = (community: Community) => {
  router.push({
    name: "CommunityHome",
    query: {
      'id': community.id
    }
  });
};

// 创建社区
const createCommunity = () => {
  router.push({
    name: "CommunityCreate"
  });
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="community-container">
    <!-- 页面标题和创建按钮 -->
    <div class="community-header">
      <h1 class="page-title">社区广场</h1>
      <van-button
        type="primary"
        icon="plus"
        class="create-btn"
        @click="createCommunity"
      >
        创建社区
      </van-button>
    </div>

    <!-- 搜索框 -->
    <div class="search-container">
      <van-search
        v-model="searchValue"
        shape="round"
        show-action
        placeholder="搜索社区"
        clearable
        @search="onSearch"
      >
        <template #action>
          <div class="search-btn" @click="onSearch(searchValue)">搜索</div>
        </template>
      </van-search>
    </div>

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="community-content">
      <!-- 我的社区部分 -->
      <div class="section-container my-communities">
        <div class="section-header">
          <h2 class="section-title">
            <van-icon name="user-circle-o" class="section-icon" />
            我的社区
          </h2>
          <van-button
            v-if="myCommunities.length > 0"
            size="small"
            plain
            class="view-all-btn"
            to="/community/my"
          >
            查看全部
          </van-button>
        </div>

        <div v-if="myCommunitiesLoading" class="loading-container">
          <van-loading size="24px" vertical>加载中...</van-loading>
        </div>

        <div v-else>
          <div v-if="myCommunities.length === 0" class="empty-container">
            <van-empty description="您还没有加入任何社区" />
            <van-button type="primary" size="small" @click="createCommunity">创建社区</van-button>
          </div>

          <div v-else class="community-grid">
            <div
              v-for="community in myCommunities.slice(0, 6)"
              :key="community.id"
              class="community-card"
              @click="navigateToCommunity(community)"
            >
              <van-image
                class="community-avatar"
                :src="community.url"
                fit="cover"
                radius="8"
              />
              <div class="community-name">{{ community.name }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 推荐社区部分 -->
      <div class="section-container recommended-communities">
        <div class="section-header">
          <h2 class="section-title">
            <van-icon name="fire-o" class="section-icon" />
            推荐社区
          </h2>
        </div>

        <div v-if="allCommunitiesLoading" class="loading-container">
          <van-loading size="24px" vertical>加载中...</van-loading>
        </div>

        <div v-else>
          <div v-if="allCommunities.length === 0" class="empty-container">
            <van-empty description="暂无推荐社区" />
          </div>

          <div v-else class="community-list">
            <div
              v-for="community in allCommunities"
              :key="community.id"
              class="community-list-item"
              @click="navigateToCommunity(community)"
            >
              <div class="community-info">
                <van-image
                  class="community-list-avatar"
                  :src="community.url"
                  fit="cover"
                  radius="8"
                />
                <div class="community-list-details">
                  <div class="community-list-name">{{ community.name }}</div>
                  <div class="community-list-description">{{ community.description || '暂无社区介绍' }}</div>
                </div>
              </div>
              <van-button
                size="small"
                type="primary"
                plain
                class="join-btn"
              >
                查看
              </van-button>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<style lang="scss" scoped>
.community-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 108px);
  background-color: #f7f8fa;

  .community-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px;
    background-color: white;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

    .page-title {
      margin: 0;
      font-size: 22px;
      font-weight: 600;
      color: #323233;
    }

    .create-btn {
      height: 36px;
      font-weight: 500;
    }
  }

  .search-container {
    padding: 0 16px;
    background-color: white;
    margin-bottom: 16px;

    .search-btn {
      padding: 0 16px;
      font-size: 14px;
      color: #1989fa;
      cursor: pointer;

      &:hover {
        color: #0570db;
      }
    }
  }

  .community-content {
    flex: 1;
    overflow-y: auto;
    padding: 0 16px 16px;
  }

  .section-container {
    background-color: white;
    border-radius: 8px;
    margin-bottom: 16px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .section-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #323233;
        display: flex;
        align-items: center;

        .section-icon {
          margin-right: 8px;
          font-size: 20px;
        }
      }

      .view-all-btn {
        font-size: 14px;
      }
    }
  }

  .loading-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    gap: 16px;
  }

  .community-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 16px;

    .community-card {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      transition: transform 0.2s;

      &:hover {
        transform: translateY(-4px);
      }

      .community-avatar {
        width: 64px;
        height: 64px;
        margin-bottom: 8px;
      }

      .community-name {
        font-size: 14px;
        text-align: center;
        color: #323233;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .community-list {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .community-list-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px;
      border-radius: 8px;
      background-color: #f8f8f8;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        background-color: #f2f3f5;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      }

      .community-info {
        display: flex;
        align-items: center;
        flex: 1;
        min-width: 0;

        .community-list-avatar {
          width: 48px;
          height: 48px;
          margin-right: 12px;
          flex-shrink: 0;
        }

        .community-list-details {
          flex: 1;
          min-width: 0;

          .community-list-name {
            font-size: 16px;
            font-weight: 500;
            color: #323233;
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .community-list-description {
            font-size: 14px;
            color: #969799;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }

      .join-btn {
        flex-shrink: 0;
      }
    }
  }
}
</style>